package com.zhanhong.opencvdemo.view;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.zhanhong.opencvdemo.R;
import com.zhanhong.opencvdemo.adapter.TextAdapter;
import com.zhanhong.opencvdemo.config.AnswerSheetConfig;
import com.zhanhong.opencvdemo.config.RecognitionConfig;
import com.zhanhong.opencvdemo.dialog.DealPhotoProgressDialog;
import com.zhanhong.opencvdemo.loader.LoaderDialog;
import com.zhanhong.opencvdemo.model.AnswerSheetModel.AnswerSheetItemModel;
import com.zhanhong.opencvdemo.presenter.MainPresenter;
import com.zhanhong.opencvdemo.presenter.MainPresenterImpl;
import com.zhanhong.opencvdemo.utils.PermissionUtils;
import com.zhanhong.opencvdemo.utils.SpUtils;
import com.zhanhong.opencvdemo.value.IntentCode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private MainPresenter mPresenter;
    private File mSourceFile;
    private boolean mConfigChange = false;
    private DealPhotoProgressDialog mProgressDialog;

    public static List<AnswerSheetItemModel> mAnswers = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermission();
        initData();
        initSetting();
        initView();
        initOpenCV();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSourceFile = null;
    }

    private void initOpenCV() {
        mPresenter.initOpenCV();
    }

    private void initData() {
        mPresenter = new MainPresenterImpl(this);
        mPresenter.initDirs();
    }

    private void initSetting() {
        EditText etQuestionCount = findViewById(R.id.et_question_count);
        int questionCount = SpUtils.readInt(SpUtils.SpType.KEY_QUESTION_COUNT);
        etQuestionCount.setText(String.valueOf(questionCount));
        etQuestionCount.addTextChangedListener(new TextAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                try {
                    Integer newCount = Integer.valueOf(s.toString());
                    if (newCount < 0) {
                        showAlertDialog("请输入有效试题数量");
                    } else if (newCount > AnswerSheetConfig.QUESTION_TOTAL_COUNT) {
                        showAlertDialog("输入的试题数量超出答题卡总题数");
                    } else {
                        SpUtils.save(SpUtils.SpType.KEY_QUESTION_COUNT, newCount);
                        mConfigChange = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        RadioGroup rgRecognitionConfig = findViewById(R.id.rg_recognition_config);
        String config = SpUtils.readString(SpUtils.SpType.KEY_RECOGNITION_CONFIG);
        if (TextUtils.equals(RecognitionConfig.RecognitionConfigName.MODE_SHARP.name(), config)) {
            rgRecognitionConfig.check(R.id.rb_sharp);
        } else if (TextUtils.equals(RecognitionConfig.RecognitionConfigName.MODE_OBTUSE.name(), config)) {
            rgRecognitionConfig.check(R.id.rb_obtuse);
        } else {
            rgRecognitionConfig.check(R.id.rb_normal);
        }
        rgRecognitionConfig.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_sharp) {
                SpUtils.save(SpUtils.SpType.KEY_RECOGNITION_CONFIG, RecognitionConfig.RecognitionConfigName.MODE_SHARP.name());
            } else if (checkedId == R.id.rb_obtuse) {
                SpUtils.save(SpUtils.SpType.KEY_RECOGNITION_CONFIG, RecognitionConfig.RecognitionConfigName.MODE_OBTUSE.name());
            } else {
                SpUtils.save(SpUtils.SpType.KEY_RECOGNITION_CONFIG, RecognitionConfig.RecognitionConfigName.MODE_NORMAL.name());
            }
            mConfigChange = true;
        });

        RadioGroup rgAnswerType = findViewById(R.id.rg_answer_type);
        if (SpUtils.readBoolean(SpUtils.SpType.KEY_SINGLE_CHOICE_QUESTION_ALL, true)) {
            rgAnswerType.check(R.id.rb_single);
        } else {
            rgAnswerType.check(R.id.rb_multi);
        }
        rgAnswerType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_multi) {
                SpUtils.save(SpUtils.SpType.KEY_SINGLE_CHOICE_QUESTION_ALL, false);
            } else {
                SpUtils.save(SpUtils.SpType.KEY_SINGLE_CHOICE_QUESTION_ALL, true);
            }
            mConfigChange = true;
        });
    }

    private void initView() {
        findViewById(R.id.btn_take_photo).setOnClickListener(v -> {
            Intent intent = new Intent(this, TakePhotoActivity.class);
            startActivityForResult(intent, IntentCode.CAMERA_REQUEST_CODE);
        });

        findViewById(R.id.btn_view_album).setOnClickListener(v -> mPresenter.viewAlbum());

        findViewById(R.id.btn_deal_photo).setOnClickListener(v -> {
            if (mSourceFile == null) {
                showAlertDialog("请先通过相机或相册传入图片");
                return;
            }
            showProgress("读取原图");
            mPresenter.dealWithPhoto(mSourceFile);
            mConfigChange = false;
        });

        findViewById(R.id.btn_view_answer).setOnClickListener(v -> {
            if (mSourceFile == null) {
                showAlertDialog("请先通过相机或相册传入图片");
                return;
            }
            if (mAnswers.size() == 0) {
                showAlertDialog("请先处理图片");
                return;
            }
            if (mConfigChange) {
                showAlertDialog("设置变更，请重新处理图片");
                return;
            }
            ResultActivity.startAction(MainActivity.this);
        });
    }

    public void onPhotoGetStart() {
        mSourceFile = null;
        mAnswers.clear();
        mConfigChange = false;
        showLoading();
    }

    public void onPhotoGetFinish(File file) {
        hideLoading();
        if (file != null) {
            mPresenter.cropPhoto(file);
        }
    }

    public void onPhotoCrop(File file) {
        mSourceFile = file;
    }

    public void onPhotoDealStart(String title) {
        showProgress(title);
    }

    public void onPhotoDealFinish(List<AnswerSheetItemModel> answers, String title, boolean success) {
        if (success) {
            if (answers != null && answers.size() > 0) {
                hideProgress();
                mAnswers.clear();
                mAnswers.addAll(answers);
                showAlertDialog("处理成功，请查看答案");
            }
        } else {
            hideProgress();
            showAlertDialog(title);
        }
    }

    private void showAlertDialog(String content) {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setCancelable(false);
        alertDialog.setTitle("提示");
        alertDialog.setMessage(content);
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "我知道了", (dialog, which) -> {
            dialog.dismiss();
        });
        alertDialog.show();
    }

    private void hideLoading() {
        LoaderDialog.stopAllLoading();
    }

    private void showLoading() {
        LoaderDialog.showLoading(this);
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showProgress(String title) {
        if (mProgressDialog == null) {
            mProgressDialog = new DealPhotoProgressDialog(this);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
        mProgressDialog.setDealProgress(title);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.handleActivityResult(requestCode, resultCode, data);
    }


    /**
     * 权限处理
     */
    private void requestPermission() {
        if (!EasyPermissions.hasPermissions(this, PermissionUtils.permissions)) {
            EasyPermissions.requestPermissions(this, "为保证Demo运行，需要申请权限", PermissionUtils.REQUEST_PERMISSION_CODE, PermissionUtils.permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showAlertDialog("权限未获取，请手动打开");
    }
}
